package com.dingding.gmall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dingding.gmall.common.utils.PageUtils;
import com.dingding.gmall.common.utils.Query;
import com.dingding.gmall.product.dao.ProductAttrValueDao;
import com.dingding.gmall.product.entity.AttrEntity;
import com.dingding.gmall.product.entity.ProductAttrValueEntity;
import com.dingding.gmall.product.service.AttrService;
import com.dingding.gmall.product.service.ProductAttrValueService;
import com.dingding.gmall.product.vo.BaseAttrs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("productAttrValueService")
public class ProductAttrValueServiceImpl extends ServiceImpl<ProductAttrValueDao, ProductAttrValueEntity> implements ProductAttrValueService {

    @Autowired
    private AttrService attrService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<ProductAttrValueEntity> page = this.page(
                new Query<ProductAttrValueEntity>().getPage(params),
                new QueryWrapper<>()
        );

        return new PageUtils(page);
    }


    @Override
    public void saveProductAttrs(Long id, List<BaseAttrs> baseAttrs) {
        if (CollectionUtils.isNotEmpty(baseAttrs)){
            List<ProductAttrValueEntity> collect = baseAttrs.stream().map(item -> {
                AttrEntity attrEntity = attrService.getById(item.getAttrId());
                return ProductAttrValueEntity.builder()
                        .attrId(item.getAttrId())
                        .attrName(attrEntity.getAttrName())
                        .attrValue(item.getAttrValues())
                        .attrSort(item.getShowDesc())
                        .spuId(id)
                        .build();
            }).collect(Collectors.toList());
            this.saveBatch(collect);
        }
    }

    @Override
    public List<ProductAttrValueEntity> baseAttrListForSpu(Long spuId) {
        return this.baseMapper.selectList(new QueryWrapper<ProductAttrValueEntity>().eq("spu_id",spuId));
    }

    @Override
    public void updateSpuAttr(Long spuId, List<ProductAttrValueEntity> entities) {
        //1、删除这个spuId之前对应的所有属性
        this.baseMapper.delete(new QueryWrapper<ProductAttrValueEntity>().eq("spu_id",spuId));

        List<ProductAttrValueEntity> collect = entities.stream().peek(item -> item.setSpuId(spuId)).collect(Collectors.toList());
        this.saveBatch(collect);
    }
}